package com.atguigu.gmall.index.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsFeign;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class IndexService {

    public static final String KEY_PREFIX = "index:category:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    @SuppressWarnings("all")
    private GmallPmsFeign pmsClient;

    @Autowired
    private RedissonClient redissonClient;

    //查询一级分类
    public List<CategoryEntity> queryLvl1Categories() {
        ResponseVo<List<CategoryEntity>> listResponseVo = this.pmsClient.queryCategory(0l);
        return listResponseVo.getData();
    }

    public List<CategoryEntity> queryLvl2CategoriesWithSub(Long pid) {
        // 从缓存中获取
        String cacheCategories = this.redisTemplate.opsForValue().get(KEY_PREFIX + pid);
        if (StringUtils.isNotBlank(cacheCategories)){
            // 如果缓存中有，直接返回
            List<CategoryEntity> categoryEntities = JSON.parseArray(cacheCategories, CategoryEntity.class);
            return categoryEntities;
        }

        ResponseVo<List<CategoryEntity>> subCategoryResp = this.pmsClient.queryCategoriesWithSub(pid);

        // 把查询结果放入缓存
        this.redisTemplate.opsForValue().set(KEY_PREFIX + pid, JSON.toJSONString(subCategoryResp.getData()), 30, TimeUnit.DAYS);

        return subCategoryResp.getData();
    }
}